<template>
  <div>
    <slot name="header"></slot>

    <attach-list v-loading="loading" :attath-data="uploadList" :show-label="showLabel">
      <slot v-for="slot in slots" :name="slot" :slot="slot"></slot>

      <template slot="tagAction" slot-scope="{ tagData }" v-if="!viewMode">
        <el-button
          type="primary"
          size="small"
          class="btn-long mb-1"
          icon="el-icon-upload2"
          @click="handleUpload(tagData.tag, tagData.parentTag)"
        >
          上传
        </el-button>
      </template>

      <template slot="attachAction" slot-scope="{ attachData }" v-if="!viewMode">
        <el-button type="text" @click="handleDeleteFile(attachData)">删除</el-button>
      </template>
    </attach-list>

    <attach-upload-dialog
      :visible.sync="uploadVisible"
      :attach-tag="uploadAttachTag"
      :parent-tag="parentTag"
      :attach-id="batchNo"
      v-bind="$attrs"
      @success="onUploadSuccess"
    ></attach-upload-dialog>
  </div>
</template>

<script>
import { attachAdapter } from '@/bank/components/attach/index'
import { deleteOss } from '@/common/api/oss'

import AttachList from '@/bank/components/attach/List'
import AttachUploadDialog from '@/bank/components/attach/UploadDialog'

export default {
  components: {
    AttachList,
    AttachUploadDialog,
  },
  props: {
    tags: {
      type: [String, Array],
      required: true,
    },
    parentTagSearch: {
      type: Boolean,
      default: false,
    },
    parentLable: {
      type: String,
      default: '',
    },
    batchNo: {
      type: String,
      default: '',
    },
    showLabel: {
      type: Boolean,
      default: true,
    },
    viewMode: Boolean,
  },
  data() {
    return {
      tableName: 'datum_customer_attachment',
      loading: false,
      uploadList: [],

      uploadAttachTag: '',
      parentTag: '',
      uploadVisible: false,
      attachTableData: [],
    }
  },
  computed: {
    uploadTags() {
      const { tags } = this
      return Array.isArray(tags) ? tags : [tags]
    },
    slots() {
      const res = []
      for (const tag of this.uploadTags) {
        if (tag.slot) res.push(tag.slot)
      }
      return res
    },
  },
  watch: {
    batchNo: {
      handler: function () {
        this.init()
      },
      immediate: true,
    },
    uploadTags() {
      this.initAttach()
    },
  },
  created() {},
  mounted() {},
  methods: {
    init() {
      this.reset()
      this.getData()
    },
    initAttach() {
      this.reset()
      for (const attach of this.attachTableData) {
        const attachData = attachAdapter(attach)

        let index = this.uploadList.findIndex(it => it.tag === attach.attachment_type)
        if (index < 0) {
          continue
        }
        this.uploadList[index].attachs.push(attachData)
      }
    },
    getData(emit = false) {
      if (!this.batchNo) {
        return
      }
      this.loading = true
      const params = {}
      if (this.parentTagSearch) {
        params['parent_attachment_type.eq'] = this.parentLable || ''
      }
      this.$api
        .getData(
          this.$serviceName,
          this.tableName,
          { 'customer_related_id.eq': this.batchNo, ...params },
          { create_time: 'desc' }
        )
        .then(res => {
          const data = res?.data ?? []
          this.attachTableData = data
          this.reset()
          const lastTag =
            this.uploadList.length - 1 > -1 ? this.uploadList[this.uploadList.length - 1] : {}

          for (const attach of data) {
            const attachData = attachAdapter(attach)
            let index = this.uploadList.findIndex(it => it.tag === attach.attachment_type)
            if (index < 0) {
              if (['其他', '其他附件', '其他立项附件'].includes(lastTag.tag)) {
                index = this.uploadList.length - 1
              } else {
                continue
              }
            }
            this.uploadList[index].attachs.push(attachData)
          }

          this.$emit('after-data', {
            list: data,
            emit,
          })
        })
        .finally(() => {
          this.loading = false
        })
    },

    reset() {
      this.uploadList = this.uploadTags.map(tag => ({
        ...tag,
        attachs: [],
      }))
    },

    handleUpload(tag, parentTag) {
      this.parentTag = parentTag
      this.uploadAttachTag = tag
      this.uploadVisible = true
    },

    onUploadSuccess(res) {
      this.getData(true)
      this.$emit('success', res)
    },

    handleDeleteFile(attach) {
      const { attachment: url, id } = attach
      this.$utils
        .msgbox({
          message: '确定删除此附件?',
          beforeClose: () => this.deleteData(id),
        })
        .then(() => {
          deleteOss(url)
          this.$message.success('删除成功！')
          this.getData(true)
          this.$emit('delete', attach)
        })
        .catch(err => {
          this.$message.error('删除失败，请重试！')
          throw new Error(err)
        })
    },

    deleteData(id) {
      return this.$api.deleteData(this.$serviceName, this.tableName, id)
    },
  },
}
</script>

<style lang="scss" scoped></style>
